//
//  MyMoyaManager.swift
//  DyhlSdk
//
//  Created by wangbo on 2021/4/8.
//

import Foundation
import Moya
import ObjectMapper
import Alamofire
@objc public class MyMoyaManager:NSObject {
    static let instance = MyMoyaManager()
    public override init(){
        
    }
    public func AllRequestNospinner<T:TargetType>(_ target:T,success successCallback: @escaping (BaseResponse) -> Void ,fail failCallback: @escaping (BaseResponse?) -> Void) {
        let provider = MoyaProvider<T>(endpointClosure: endpointMapping ,requestClosure: requestClosure)
        provider.request(target) { (event) in
            switch event {
            case let .success(response):
                do {
                    let data = try response.mapJSON() as! [String:Any]
                    if let u = BaseResponse(JSON: data){
                        if u.code ?? 0 == 200{
                            successCallback(u)
                        }else  {
                            log.warning(u.toJSONString() ?? "")
                            failCallback(u)
                        }
                    }else{
                        log.warning(data.debugDescription )
                        failCallback(nil)
                    }
                } catch {
                    //可不做处理
                    log.error(error.localizedDescription)
                }
                break
            case let .failure(error):
                failCallback(nil)
                log.error(error.failureReason ?? "")
                break
            }
        }
    }
    @objc public func getevent(json:String,success successCallback: @escaping (BaseResponse) -> Void ,fail failCallback: @escaping (BaseResponse?) -> Void){
        MyMoyaManager.instance.AllRequestNospinner(NetworkService.allRequest(json: json)) { (data) in
            successCallback(data)
        } fail: { (faildata) in
            failCallback(faildata)
        }

        
    }
}
public func moyascratyManager() -> Manager?{
    var manager :Manager
    if ApiKey.instance.版本环境 == "测试版本" {
        manager = MoyaProvider<MultiTarget>.defaultAlamofireManager()
        manager.delegate.sessionDidReceiveChallenge = {
            session,challenge in
            return    (URLSession.AuthChallengeDisposition.useCredential,URLCredential(trust:challenge.protectionSpace.serverTrust!))
        }
    }else{
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders
        //    let path: String = Bundle.main.path(forResource: "apphttps", ofType: "cer") ?? ""
        let path:String = Bundle.main.path(forResource: "90btm", ofType: ".cer") ?? ""
        guard  let certificationData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData else {
            return nil
        }
        guard let certificate = SecCertificateCreateWithData(nil, certificationData) else { return nil }
        let certificates: [SecCertificate] = [certificate]
        
        let policies : [String:ServerTrustPolicy] = ["90btm": ServerTrustPolicy.pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true )]
        manager = Manager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
    }
    return manager
}
public func endpointMapping<Target: TargetType>(target: Target) -> Endpoint {
    log.verbose("Moya请求连接：____   \(target.baseURL)/\(target.path)   ___________   \(target.method)")
    return MoyaProvider.defaultEndpointMapping(for: target)
}
public let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        //设置请求时长
        request.timeoutInterval = 30
        // 打印请求参数
        if let requestData = request.httpBody {
            log.verbose("\(request.url!)"+"\n"+"\(request.httpMethod ?? "")"+"发送参数"+"\(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
        }else{
            log.verbose("\(request.url!)"+"\(String(describing: request.httpMethod))")
        }
        done(.success(request))
    } catch {
        done(.failure(MoyaError.underlying(error, nil)))
    }
}
